<template>
  <div class="category-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分类管理</span>
          <el-button type="primary" @click="handleAdd">新增分类</el-button>
        </div>
      </template>

      <!-- 分类树形表格 -->
      <el-table
        v-loading="loading"
        :data="categoryList"
        row-key="id"
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="分类名称" min-width="200">
          <template #default="{ row }">
            <span>{{ row.name }}</span>
            <el-tag v-if="!row.parentId" size="small" type="success" class="ml-2">{{ row.dimension }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dimension" label="维度" width="120" />
        <el-table-column prop="sort" label="排序" width="100" align="center" />
        <el-table-column label="显示状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.showStatus === 1 ? 'success' : 'info'">
              {{ row.showStatus === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="可见性" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.visible === 1 ? 'success' : 'info'">
              {{ row.visible === 1 ? '可见' : '不可见' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="primary" link @click="handleAddSub(row)">添加子分类</el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(row)"
                :disabled="hasChildren(row)"
              >删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分类表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      destroy-on-close
      @close="resetForm"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="父级分类" v-if="dialogType === 'add-sub'">
          <el-input v-model="parentCategory.name" disabled />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="维度" prop="dimension" v-if="!categoryForm.parentId">
          <el-select v-model="categoryForm.dimension" placeholder="请选择维度">
            <el-option label="一次元" value="一次元" />
            <el-option label="二次元" value="二次元" />
            <el-option label="三次元" value="三次元" />
            <el-option label="跨次元" value="跨次元" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="显示状态">
          <el-radio-group v-model="categoryForm.showStatus">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可见性">
          <el-radio-group v-model="categoryForm.visible">
            <el-radio :label="1">可见</el-radio>
            <el-radio :label="0">不可见</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCategoryTree,
  createCategory,
  updateCategory,
  deleteCategory
} from '@/api/category'

// 状态定义
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const dialogTitle = ref('新增分类')
const categoryFormRef = ref(null)
const categoryList = ref([])
const parentCategory = ref({})

// 表单数据
const categoryForm = reactive({
  id: undefined,
  parentId: undefined,
  name: '',
  dimension: '',
  sort: 0,
  showStatus: 1,
  visible: 1,
  level: undefined
})

// 表单校验规则
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  dimension: [
    { required: true, message: '请选择维度', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', message: '排序值必须为数字', trigger: 'blur' }
  ]
}

// 获取分类树
const fetchCategoryTree = async () => {
  try {
    loading.value = true
    const res = await getCategoryTree()
    if (res?.code === 200) {
      categoryList.value = res.data || []
    } else {
      ElMessage.warning(res?.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 新增分类
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增分类'
  categoryForm.parentId = undefined
  categoryForm.level = 1
  dialogVisible.value = true
}

// 添加子分类
const handleAddSub = (row) => {
  dialogType.value = 'add-sub'
  dialogTitle.value = '新增子分类'
  parentCategory.value = row
  categoryForm.parentId = row.id
  categoryForm.dimension = row.dimension
  categoryForm.level = row.level + 1
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑分类'
  Object.assign(categoryForm, row)
  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (row) => {
  if (hasChildren(row)) {
    ElMessage.warning('该分类下有子分类，不能删除')
    return
  }

  try {
    await ElMessageBox.confirm('确认要删除该分类吗？', '警告', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    await deleteCategory(row.id)
    ElMessage.success('删除成功')
    fetchCategoryTree()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!categoryFormRef.value) return

  try {
    await categoryFormRef.value.validate()
    submitting.value = true

    if (dialogType.value === 'edit') {
      await updateCategory(categoryForm.id, categoryForm)
      ElMessage.success('更新成功')
    } else {
      await createCategory(categoryForm)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchCategoryTree()
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败：' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }
  Object.assign(categoryForm, {
    id: undefined,
    parentId: undefined,
    name: '',
    dimension: '',
    sort: 0,
    showStatus: 1,
    visible: 1,
    level: undefined
  })
  parentCategory.value = {}
}

// 检查是否有子分类
const hasChildren = (row) => {
  return row.children && row.children.length > 0
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return '暂无'
  const [year, month, day, hour, minute, second] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 初始化
onMounted(() => {
  fetchCategoryTree()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ml-2 {
  margin-left: 8px;
}

:deep(.el-input-number) {
  width: 120px;
}

:deep(.el-select) {
  width: 100%;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
</style> 